#include "stdinc.h"
#include <fstream>

#include "Main/Logger.h"





using namespace Main;


size_t Logger::QueueLength = 1000;

Logger *Ogre::Singleton<Logger>::ms_Singleton = 0;

Logger &Logger::getSingleton()
{
	return *ms_Singleton;
}



Logger::~Logger()
{
	mMessages.clear();
	mListeners.clear();
}


void Logger::logMessage(std::string &message,std::string &source)
{
	if (mMessages.size() >= QueueLength)
		mMessages.pop_front(); 
		
	LogMessage msg(message,source);

	for (std::list<LogListener*>::iterator i = mListeners.begin(); i != mListeners.end(); ++i)
				(*i)->receiveLogMessage(msg.message,msg.timestamp ,msg.source);

	mMessages.push_back(msg);

}

void Logger::registerListener(Main::LogListener *listener,bool includeHistory)
{
	
	for (std::list<LogListener*>::iterator i = mListeners.begin(); i != mListeners.end(); ++i)
		if ( (*i) == listener) return;

	mListeners.push_back(listener);

	if (!includeHistory) return;

	for (std::list<LogMessage>::iterator i = mMessages.begin(); i != mMessages.end(); ++i)
		listener->receiveLogMessage((*i).message,(*i).timestamp,(*i).source);
}



void FileLogListener::receiveLogMessage(const std::string message,time_t timestamp,const std::string source)
{
	char timebuf[50];
	_strtime_s(timebuf,50);
	std::fstream f(mFileName.c_str(),std::ios_base::out|std::ios_base::app);
	if (!f.is_open()) return;
	f << "[" << source << " @" << timebuf << ":" << message << std::endl;

	f.close();
}

FileLogListener::FileLogListener(std::string fileName) :mFileName(fileName) 
{
	std::fstream f(mFileName.c_str(),std::ios_base::out|std::ios_base::trunc);
	f.close();
}